<?php

namespace app\api\controller\sharing;

use app\api\controller\Controller;
use app\api\model\sharing\Active as ActiveModel;
use app\api\model\sharing\Goods as GoodsModel;
use app\common\model\sharing\UserRedBag;

/**
 * 拼团拼单控制器
 * Class Active
 * @package app\api\controller\sharing
 */
class Active extends Controller
{
    /**
     * 拼单详情
     * @param $active_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail($active_id)
    {
        // 拼单详情
        $detail = ActiveModel::detail($active_id);
        if (!$detail) {
            return $this->renderError('很抱歉，拼单不存在');
        }

        $detail = $detail->toArray();
        // LLH 查询是否已经开奖
        $model  = new UserRedBag;
        $u = $model->where("active_id",$active_id)->field(["user_id"])->select()->toArray();
        $a_user = [];
        if(!empty($u)){
            $a_user = array_column($u,"user_id");
        }

        $me = $this->getUser(false);
        foreach ($detail['users'] as $key => $detail_value){
            if(empty($a_user)){
                $detail['users'][$key]['is_win'] = 2;
            }else{
                $detail['users'][$key]['is_win'] = 1;
                if(in_array($detail_value['user_id'],$a_user)){
                    $detail['users'][$key]['is_win'] = 0;
                }
            }
        }

        // LLH 是否为自己中奖
        $custom = [
            "is_win" => in_array($me['user_id'], $a_user) ? 0 : 1
        ];
        // 拼团商品详情
        $model = new GoodsModel;
        $goods = $model->getDetails($detail['goods_id'], $this->getUser(false));
        // 更多拼团商品
        $goodsList = $model->getList([], $me);
        return $this->renderSuccess(compact('detail', 'goods', 'goodsList',"custom"));
    }

}
